import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
// 导入API层和类型
import * as aiApi from '@/api/ai'
import type { ChatSession, ChatMessage } from '@/api/ai'
import { useUserStore } from './user'

// 新增：扩展 ChatSession 类型，确保包含 userId 字段
type ChatSessionWithUserId = ChatSession & { userId?: string | number }

export const useAiChatStore = defineStore('aiChat', () => {
  const userStore = useUserStore()
  // --- State ---
  const chatHistory = ref<ChatSession[]>([])
  const currentChatId = ref<string | null>(null)
  const currentMessages = ref<ChatMessage[]>([])
  
  const isStreaming = ref(false)
  const isLoadingHistory = ref(false)
  const isLoadingMessages = ref(false)

  // --- Getters (计算属性) ---
  const currentChat = computed(() => {
    return chatHistory.value.find(chat => chat.id === currentChatId.value)
  })

  // --- Actions (方法) ---

  // 开始一个新会话
  const startNewChat = async () => {
    console.log('startNewChat 方法开始执行')
    
    if (isLoadingHistory.value || isLoadingMessages.value) {
      console.log('正在加载中，取消创建新会话')
      return
    }
    
    try {
      console.log('准备调用 createChatSession API')
      const userId = userStore.id
      if (!userId) {
        console.error('用户未登录，无法创建会话')
        throw new Error('用户未登录')
      }
      console.log('id:', userId)
      const response = await aiApi.createChatSession('新会话', userId)
      console.log('创建会话响应:', response)
      
      if (response && response.code === 200 && response.data) {
        const newSession = response.data as ChatSessionWithUserId
        if (!newSession.id) {
          console.error('新会话数据不完整:', newSession)
          throw new Error('会话数据不完整')
        }
        
        // 新增：userId 字段赋值
        const newSessionForHistory: ChatSessionWithUserId = {
          id: newSession.id,
          title: newSession.title,
          createdAt: newSession.createdAt,
          updatedAt: newSession.updatedAt,
          userId: newSession.userId // 兼容后端返回
        }
        
        chatHistory.value.unshift(newSessionForHistory)
        currentChatId.value = newSession.id
        currentMessages.value = []
        
        console.log('新会话创建成功，ID:', newSession.id)
        return newSession.id
      } else {
        console.error('创建会话失败，响应结构不正确:', response)
        throw new Error(response?.message || '创建会话失败')
      }
    } catch (error) {
      console.error('创建新会话失败:', error)
      throw error
    }
  }

  // 加载会话历史列表
  const loadChatHistory = async () => {
    if (isLoadingHistory.value) {
      console.log('正在加载历史记录，跳过重复请求')
      return
    }

    try {
      isLoadingHistory.value = true
      console.log('开始加载会话历史')

      // 获取用户id
      const userId = userStore.id ? Number(userStore.id) : undefined
      const response = await aiApi.getChatHistory(userId)
      if (response && response.code === 200 && response.data) {
        const responseData = response.data
        if (responseData.sessions && Array.isArray(responseData.sessions)) {
          chatHistory.value = responseData.sessions.sort((a, b) =>
            new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
          )
          if (!currentChatId.value && chatHistory.value.length > 0) {
            await loadChat(chatHistory.value[0].id)
          }
        } else {
          console.error('历史记录响应数据格式不正确:', responseData)
          chatHistory.value = []
        }
      } else {
        console.error('加载历史记录失败，响应:', response)
        chatHistory.value = []
      }
    } catch (error) {
      console.error('加载聊天历史失败:', error)
      chatHistory.value = []
    } finally {
      isLoadingHistory.value = false
    }
  }

  // 加载指定会话的消息
  const loadChat = async (sessionId: string) => {
    if (isLoadingMessages.value || !sessionId) return
    // 立即清空旧消息并设置当前会话ID
    currentChatId.value = sessionId
    currentMessages.value = []
    try {
      isLoadingMessages.value = true
      // 获取用户id
      const userId = userStore.id ? Number(userStore.id) : undefined
      const response = await aiApi.getChatMessages(sessionId, userId)
      if (response && response.code === 200 && response.data) {
        const responseData = response.data
        if (responseData.messages && Array.isArray(responseData.messages)) {
          currentMessages.value = responseData.messages
        } else {
          currentMessages.value = []
        }
      } else {
        console.error('加载消息失败，响应:', response)
        currentMessages.value = []
      }
    } catch (error) {
      console.error(`加载会话 ${sessionId} 失败:`, error)
      currentChatId.value = null
      currentMessages.value = []
    } finally {
      isLoadingMessages.value = false
    }
  }

  // 发送消息
  const sendMessage = async (prompt: string) => {
    if (!currentChatId.value) {
      console.error('没有当前会话ID，无法发送消息')
      throw new Error('请先创建或选择一个会话')
    }

    if (isStreaming.value) {
      console.log('正在发送消息中，跳过重复请求')
      return
    }

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      role: 'user',
      content: prompt,
      timestamp: new Date().toISOString(),
      username: userStore.user?.nickname,
      avatar: userStore.user?.avatar
    }

    currentMessages.value.push(userMessage)

    try {
      isStreaming.value = true
      const response = await aiApi.sendMessage(prompt, currentChatId.value)
      if (response && response.code === 200 && response.data) {
        const aiMessage = response.data
        const aiMessageForDisplay: ChatMessage = {
          id: aiMessage.id,
          role: 'assistant',
          content: aiMessage.content,
          timestamp: aiMessage.timestamp,
        }
        currentMessages.value.push(aiMessageForDisplay)
      } else {
        console.error('AI回复失败，响应:', response)
        throw new Error(response?.message || 'AI回复失败')
      }
    } catch (error) {
      console.error('发送消息失败:', error)
      if (error.code === 'ERR_NETWORK') {
        throw new Error('网络连接失败，请检查后端服务是否启动')
      } else {
        throw error
      }
    } finally {
      isStreaming.value = false
    }
  }

  // 删除会话
  const removeChatSession = async (sessionId: string) => {
    try {
      await aiApi.deleteChatSession(sessionId)
      const index = chatHistory.value.findIndex(s => s.id === sessionId)
      if (index !== -1) {
        chatHistory.value.splice(index, 1)
      }
      if (currentChatId.value === sessionId) {
        currentChatId.value = null
        currentMessages.value = []
        if (chatHistory.value.length > 0) {
          await loadChat(chatHistory.value[0].id)
        }
      }
    } catch (error) {
      console.error(`删除会话 ${sessionId} 失败:`, error)
    }
  }

  // 更新标题
  const editSessionTitle = async (sessionId: string, newTitle: string) => {
    try {
      await aiApi.updateSessionTitle(sessionId, newTitle)
      const session = chatHistory.value.find(s => s.id === sessionId)
      if (session) {
        session.title = newTitle
      }
    } catch (error) {
      console.error(`更新标题失败:`, error)
    }
  }

  return {
    chatHistory,
    currentChatId,
    currentMessages,
    isStreaming,
    isLoadingHistory,
    isLoadingMessages,
    currentChat,
    loadChatHistory,
    loadChat,
    startNewChat,
    sendMessage,
    removeChatSession,
    editSessionTitle,
  }
})
